/**
 * 
 */

module.exports = function(tableName){
	
	this.tableName = tableName || null;
	this.db = null;

	/**
	 * 使用M保存当前的对象引用
	 */
	var M = this;

	/**
	 * 实例化Database对象
	 */
	if(this.tableName){
		console.log("to open database...")
		var sqlite3 = require('sqlite3').verbose();
		this.db = new sqlite3.Database('blog_2013.s3db', function(){
			M.onOpen();
		});
	}

	this.onOpen = function(err){
		if(err){
			err.message = "can not open database: " + err.message;
			throw err;
		}
	}

	this.getName = function(){
		return this.tableName;
	}

	this.save = function(data, callback){
		var columns = M.buildColumns(data);

		var sql = "insert into " + this.tableName + " " + columns ;

		var params = new Array();
		var index = 0;
		for(var key in data){
			params[index++] = data[key];
		}
		console.log(sql);
		console.log(params);

		M.db.run(sql, params, typeof(callback) == 'function' ? callback : M.defaultCallback);
	}

	this.defaultCallback = function(err){
		if(err){
			err.message = "db work error: " + err.message;
			throw err;
		}
		console.log("database work success!");
	}

	this.buildColumns = function(data){
		var columns = "(";
		var values = " values (";
		for(var key in data){
			columns += key + ",";
			values +=  "?,";
		}

		return columns.substring(0, columns.length - 1) + ")" 
				+ values.substring(0, values.length - 1) + ")";
	}
};